// Author: Tim Grant

package CSISL4pk;

public class ParseStringFunctions {
    
    // make sure class cannot be instantiated
    private ParseStringFunctions() {
        throw new AssertionError();
    }

    /*
     * This method takes a string and converts each single quote
     * to two single quotes in order to prevent SQL injection when
     * saving to the database.
     */
    public static String parseStringOut(String input) {

        String output = "";
        char nextCh;

        for (int index = 0; index < input.length(); index++) {
            try {
                nextCh = input.charAt(index);
                if (nextCh == '\'') {
                    output += "\'\'";
                } else {
                    output += nextCh;
                }
            } catch (IndexOutOfBoundsException ex) {
                throw new IndexOutOfBoundsException("End of String.");
            }
        }
        return output;
    } // end parseStringOut()

    /*
     * This method takes a string and replaces each pair of
     * single quotes with one single quote.
     */
    public static String parseStringIn(String input) {

        String output = "";
        char nextCh;
        boolean quoteFlag = false;

        for (int index = 0; index < input.length(); index++) {
            try {
                nextCh = input.charAt(index);
                if (nextCh == '\'') {
                    if (quoteFlag) {
                        output += nextCh;
                        quoteFlag = false;
                    } else {
                        quoteFlag = true;
                    }
                } else {
                    output += nextCh;
                }
            } catch (IndexOutOfBoundsException ex) {
                throw new IndexOutOfBoundsException("End of String.");
            }
        }
        return output;
    }// end parseStringIn()
}
